/*
  需求：给整个页面添加背景水印。

  思路：
    1、使用 canvas 特性生成 base64 格式的图片文件，设置其字体大小，颜色等。
    2、将其设置为背景图片，从而实现页面或组件水印效果
  
  使用：设置水印文案，颜色，字体大小即可
  <div v-waterMarker="{text:'版权所有',textColor:'rgba(180, 180, 180, 0.4)'}"></div>
*/
import { useConfigStore } from '@/store/modules/config.js'  // store

const addWaterMarker = (str, parentNode, font, textColor) => {
  // 水印文字，父元素，字体，文字颜色
  let can = document.createElement('canvas')
  parentNode.appendChild(can)
  can.width = 205
  can.height = 140
  can.style.display = 'none'
  let ctx = can.getContext('2d')
  ctx.rotate((-20 * Math.PI) / 180)
  ctx.font = font || '16px Microsoft JhengHei'
  ctx.fillStyle = textColor || 'rgba(180, 180, 180, 0.3)'
  ctx.textAlign = 'left'
  ctx.textBaseline = 'Middle'
  ctx.fillText(str, can.width / 10, can.height / 2)
  parentNode.style.backgroundImage = `url(${can.toDataURL('image/png')})`
}

const addWaterMarkerLine = (str, parentNode, font, textColor) => {
  // 水印文字，父元素，字体，文字颜色
  let can = document.createElement('canvas')
  parentNode.appendChild(can)
  can.width = 360
  can.height = 250
  can.style.display = 'none'
  let ctx = can.getContext('2d')
  ctx.rotate((-20 * Math.PI) / 180)
  ctx.font = font || '16px Microsoft JhengHei'
  ctx.fillStyle = textColor || 'rgba(180, 180, 180, 0.3)'
  ctx.textAlign = 'left'
  ctx.textBaseline = 'Middle'
  let lines = str.split('\n');
  let y = can.height / 2;
  let lineHeight = ctx.measureText('M').width + 10;
  // 绘制多行水印
  // console.log(lines)
  lines.forEach(function (line) {
    ctx.fillText(line, can.width / 2, y);
    y += lineHeight;
  });
  parentNode.style.backgroundImage = `url(${can.toDataURL('image/png')})`
}

const waterMarker = {
  mounted(el, binding) {
    const configStoreData = useConfigStore()

    let waterMarkerConfig = configStoreData.configList.filter(item => item.configKey === 'sys.waterMarker')[0]

    if (waterMarkerConfig && waterMarkerConfig.configValue === 'false') {
      return
    }

    // addWaterMarker(binding.value.text, el, binding.value.font, binding.value.textColor)
    addWaterMarkerLine(binding.value.text, el, binding.value.font, binding.value.textColor)
  }
}

export default waterMarker
